package com.neo.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.neo.dao.SetmealDao;
import com.neo.entity.PageResult;
import com.neo.entity.QueryPageBean;
import com.neo.pojo.Setmeal;
import com.neo.service.SetmealService;
import com.neo.utils.QiniuUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.pageQuery(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐
        setmealDao.add(setmeal);
        //添加关联
        setAssociationSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
    }

    private void setAssociationSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        if (ArrayUtils.isNotEmpty(checkgroupIds)) {
            Map<String, Integer> map = null;
            for (Integer checkgroupId : checkgroupIds) {
                map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealIdAndCheckGroupId(map);
            }
        }
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return setmealDao.findCheckGroupIdsBySetmealId(setmealId);
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Transactional
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //更新套餐
        setmealDao.update(setmeal);
        //删除关联
        setmealDao.deleteCheckGroupIdsBySetmealId(setmeal.getId());
        //建立关联
        setAssociationSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
    }


    @Transactional
    @Override
    public String delete(Integer id) {
        //删除关联
        setmealDao.deleteCheckGroupIdsBySetmealId(id);
        Setmeal setmeal = setmealDao.findById(id);
        //删除套餐
        setmealDao.deleteById(id);
        return setmeal == null ? null : setmeal.getImg();
    }

}
